<?php
/**
 * Created by PhpStorm.
 * User: Yieong
 * Date: 14/11/18
 * Time: 上午9:36
 */


class MenuService extends Service {

    /**
     * 根据菜单ID返回信息
     * @param $menuId    菜单ID
     * @return array|mixed|null|void
     */
    public static function getMenuById($menuId){
        $modMenu = new ModMenu();

        $menu = $modMenu->findByPk($menuId)->attributes;
        $menu['Function'] = $menu['Function'];

        return $menu;
    }

    /**
     * 菜单表头
     * @return array
     */
    public static function indexHeader(){
        $header = array(
            'MenuID'            => array('text' => PubFunc::t('菜单编号')),
            'MenuName'          => array('text' => PubFunc::t('菜单名称')),
        	'Visible'           => array('text' => PubFunc::t('显示'),'width' => '50px'),
            'SortNum'           => array('text' => PubFunc::t('排序号'),'width' => '80px'),
            'Action'            => array('text' => PubFunc::t('操作'))
        );

        return $header;
    }

    /**
     * 菜单信息
     * @param $params
     *      app     应用ID，必填
     *      pid     父菜单信息
     *      search  查询信息
     * @return array
     */
    public static function indexData($params){
        $modMenu = new ModMenu();
        $tmp = $modMenu->page($params);

        $result = array();

        $nextText   = PubFunc::t('子菜单');
        $editText   = PubFunc::t('编辑');
        $deleteText = PubFunc::t('删除');
        $confirm    = PubFunc::t('是否确定要删除这个菜单？');

        foreach($tmp['data'] as $v){
            $action = "<a href='/auth/?r=menu/index&pid={$v['MenuID']}&g={$params['g']}&m={$params['m']}'>{$nextText}&nbsp;&nbsp;</a>";
            $action .= "<a href='/auth/?r=menu/edit&id={$v['MenuID']}&page={$params['page']}&g={$params['g']}&m={$params['m']}'>{$editText}&nbsp;&nbsp;</a>";
            $action .= "<a href='/auth/?r=menu/delete&id={$v['MenuID']}&page={$params['page']}&pid={$params['pid']}&g={$params['g']}&m={$params['m']}' confirm='{$confirm}'>{$deleteText}&nbsp;&nbsp;</a>";

            $visible = "";
            if($v['Visible'] == 1) {
            	$visible = "<span class='changeVisible yes' data-id='".$v['MenuID']."'><i class='fa fa-check-circle'></i>是</span>";
            }
            if($v['Visible'] == 2){
            	$visible = "<span class='changeVisible no' data-id='".$v['MenuID']."'><i class='fa fa-ban'></i>否</span>";
            }
            
            $sortNum = "<input class='changeSortNum' type='text' size='3' style='text-align: center;' value='".$v['SortNum']."' data-id='".$v['MenuID']."' ";

            $result[] = array(
                'MenuID'    => $v['MenuID'],
                'MenuName'  => $v['MenuName'],
            	'Visible'   => $visible,
                //'SortNum'   => $v['SortNum'],
            	'SortNum'   => $sortNum,
                'Action'    => $action
            );
        }
        $tmp['data'] = $result;
        return $tmp;
    }

    /**
     * 导航面包屑
     * @param $app      应用ID
     * @param $menuId   当前菜单ID
     * @return array
     */
    public static function getBreadCrumb($menuId){
        $path = array();

        if($menuId != 'R0'){
            $modMenu = new ModMenu();
            $result = array();
            foreach($modMenu->select() as $v){
                $result[$v['MenuID']] = $v;
            }

            $maxCnt = 20;
            $currentId = $menuId;
            while($maxCnt-- > 0 && isset($result[$currentId])){
                $currentMenu = $result[$currentId];
                $currentId  = $currentMenu['ParentID'];

                $path[] = array(
                    'MenuID'    => $currentMenu['MenuID'],
                    'MenuName'  => $currentMenu['MenuName']
                );
            }
        }

        $path[] = array('MenuID' => 'M0', 'MenuName' => PubFunc::t('根节点'));

        $path = array_reverse($path);

        unset($path[count($path) - 1]['MenuID']);

        return $path;
    }

    /**
     * 添加菜单
     * @param $menu
     * @return bool
     */
    public static function add($menu){
        $modMenu = new ModMenu();

        $modMenu->MenuID        = LibModel::getNewId($modMenu, 'MenuID', 'M');
        $modMenu->MenuName      = $menu['menuname'];
        $modMenu->ParentID      = $menu['pid'];
        $modMenu->SortNum       = $menu['sort'];
        $modMenu->Status        = 1;
        $modMenu->Visible       = $menu['isview'];
        $modMenu->MenuUrl       = $menu['url'];
        $modMenu->MenuIcon      = $menu['icon'];
        $modMenu->Function      = $menu['function'];

        PubFunc::addBy($modMenu);

        return $modMenu->save();
    }
    public static function edit($menu){
        $id = $menu['id'];
        $attr = array(
            'MenuName'      => $menu['menuname'],
            'ParentID'      => $menu['pid'],
            'SortNum'       => $menu['sort'],
            'Status'        => $menu['status'],
            'Visible'       => $menu['isview'],
            'MenuUrl'       => $menu['url'],
            'MenuIcon'      => $menu['icon'],
            'Function'      => htmlspecialchars_decode($menu['function'])
        );

        PubFunc::editBy($attr);

        try{
            $modMenu = new ModMenu();
            $modMenu->updateByPk($id, $attr);
            return true;
        }catch (Exception $e){
            return false;
        }

    }
    
    public static function change_field($id,$field,$value){
    	$attr = array(
    			$field      => $value,
    	);
    	try{
    		$modMenu = new ModMenu();
    		$modMenu->updateByPk($id, $attr);
    		return true;
    	}catch (Exception $e){
    		return false;
    	}
    
    }
    
    

    /**
     * 删除菜单
     * @param $id
     * @return bool
     */
    public static function delete($id){
        self::beginTransaction();
        try{
            ModMenu::model()->deleteByPk($id);
            ModRoleMenuMap::model()->deleteAllByAttributes(array('MenuID' => $id));
            self::commit();
            return true;
        }catch (Exception $e){
            echo $e->getMessage();die;
            self::rollback();
            return false;
        }

    }


    /**
     * 父节点选项
     * @param $app
     * @return array
     */
    public static function menuOptions(){
        $modMenu = new ModMenu();
        $tmp = $modMenu->select();

        $options = array();
        foreach($tmp as $v){
            $options[$v['MenuID']] = $v['MenuName'];
        }

        return array(
            'M0' => PubFunc::t('根节点')
        ) + $options;
    }

    /**
     * 是否显示选项
     * @return array
     */
    public static function viewOptions(){
        return array(
            '1' => PubFunc::t('显示'),
            '2' => PubFunc::t('隐藏'),
        );
    }

    /**
     * 状态选项
     * @return array
     */
    public static function statusOptions(){
        return array(
            '1' => PubFunc::t('正常'),
            '2' => PubFunc::t('停用'),
        );
    }

    public static function getNextSort($pid){
        return ModMenu::model()->getMaxSort($pid) + 1;
    }

    public static function getUserMenu($userId){
        return ModMenu::getUserMenu($userId);
    }
    
    public static function getRoleMenu($roleId){
    	return ModMenu::getRoleMenu($roleId);
    }

} 